import React, {Component } from 'react';
import { Card ,Form, Input, Button, Select, message } from 'antd';
import {ArrowLeftOutlined } from '@ant-design/icons';
import {reqCategoryList, reqCategoryInfo,reqAddProduct,reqUpdateProduct} from '../../../api'
import PictureWall from '../picture_wall/PictureWall.jsx'
import RichTextEdit from "../rich_text_edit/richTextEdit.jsx";

class AddUpdate extends Component {
  form = React.createRef()
  state = {
    categoryList: [],  // 分类列表
    categoryName: '',  // 根据id获取的分类name
    richText: '',  // 富文本编辑器内容
    pictureNameList: []  //图片name数组
  };
  render() {
    const {categoryList,categoryName } = this.state;
    return <Card title={<div><ArrowLeftOutlined style={{color:'#1DA57A'}} onClick={()=>{this.props.history.goBack()}}/> {this.props.location.state?"商品修改":"商品添加"}</div>}>
      <Form
        labelCol={{ span: 2 }}
        wrapperCol={{ span: 14 }}
        onFinish={this.onFinish}
        onFinishFailed={this.onFinishFailed}
        ref={this.form}
      >
        <Form.Item
          label="商品名称"
          name="name"
          rules={[{ required: true, message: '商品名称必须输入！' }]}
        >
          <Input placeholder="商品名称"/>
        </Form.Item>
        <Form.Item
          label="商品描述"
          name="desc"
          rules={[{ required: true, message: '商品描述必须输入！' }]}
        >
          <Input placeholder="商品描述"/>
        </Form.Item>
        <Form.Item
          label="商品价格"
          name="price"
          rules={[{ required: true, message: '商品价格必须输入！' }]}
        >
          <Input placeholder="商品价格" addonAfter="元"/>
        </Form.Item>
        <Form.Item
          label="商品分类"
          name="categoryId"
          rules={[{ required: true, message: '商品分类必须选择！' }]}
        >
          <Select placeholder={categoryName?categoryName:"请选择分类"}>
            {
              categoryList.map(item => {
                return <Select.Option value={item._id} key={item._id}>{item.name}</Select.Option>
              })
            }
          </Select>
        </Form.Item>
        <Form.Item label="商品图片">
          <PictureWall childrenPicture={this.childrenPicture}/>
        </Form.Item>
        <Form.Item label="商品详情" wrapperCol={{ span: 20 }}>
          <RichTextEdit childrenRichText={this.childrenRichText} txt={this.props.location.state?this.props.location.state.detail:''}/>
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit">
            提交
          </Button>
        </Form.Item>
      </Form>
    </Card>
  }
  componentDidMount() {
    let data = this.props.location.state;
    if (data) {  // 如果有值，是修改页面
      this.setState({  // 先将原来的值传给richText和imgs，如果后期没有修改，提交时拿到原来值，后期修改，提交时则是修改值
        richText: data.detail,
        pictureNameList: data.imgs
      })
      this.form.current.setFieldsValue({  //设置表单值
        name: data.name,
        price: data.price,
        desc: data.desc,
      })
  
      // 根据分类ID获取分类
      this.getCategoryInfo()
    }
    
    // 获取分类列表
    this.getCategoryList()
  }
  
  // 子组件上传的图片name列表
  childrenPicture = (pictureList) => {
    this.setState({
      pictureNameList: pictureList
    })
  }
  
  // 子组件富文本编辑器中内容
  childrenRichText = (text) => {
    this.setState({
      richText: text
    })
  }
  
  // 提交时，form表单验证成功，添加或修改商品
  onFinish = async values => {
    let {richText,pictureNameList} = this.state
    
    if (this.props.location.state) {  // 更新修改页面
      let id = this.props.location.state._id
      console.log({...values,detail:richText,imgs:pictureNameList,_id:id})
      let res = await reqUpdateProduct({...values,detail:richText,imgs:pictureNameList,_id:id})
      let {status, msg} = res
      if (status === 0) {  //修改成功
        message.success('修改成功!',1)
        this.props.history.goBack()
      } else {   //修改失败
        message.error(msg,1)
      }
    } else {   //添加页面
      let res = await reqAddProduct({...values,detail:richText,imgs:pictureNameList})
      let {status, msg} = res
      if (status === 0) {   // 添加商品成功
        message.success('添加商品成功',1)
        this.props.history.push('/admin/prod_about/product')
      } else { //添加商品失败
        message.success(msg,1)
      }
    }
  };
  
  // 提交时，form表单验证失败
  onFinishFailed = errorInfo => {
    message.error(errorInfo.errorFields[0].errors[0])
  };
  
  // 获取分类列表
  getCategoryList = async() => {
    let res = await reqCategoryList()
    let {status, data, msg} = res
    if (status === 0) {  // 请求成功
      this.setState({
        categoryList: data
      })
    } else {  // 请求失败
      message.error(msg, 1)
    }
  }
  
  // 根据分类ID获取分类
  getCategoryInfo = async () => {
    let categoryId = this.props.location.state.categoryId;
    let res = await reqCategoryInfo(categoryId);
    let {status, data, msg} = res;
    if (status === 0) {  // 请求成功
      this.form.current.setFieldsValue({
        categoryId:data._id
      })
      this.setState({
        categoryName:data.name
      })
    } else {  // 请求失败
      message.error(msg, 1)
    }
  }
  
}

export default AddUpdate;
